package com.cy.spring;

import org.omg.PortableInterceptor.Interceptor;

import java.beans.Introspector;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class WdpApplicationContext {

    private Class appConfig;

    private ConcurrentHashMap<String,BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String,Object> singletonObjects = new ConcurrentHashMap<>();
    private List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    public WdpApplicationContext(Class appConfig) {
        this.appConfig = appConfig;

        if (appConfig.isAnnotationPresent(ComponentScan.class)) {
            //扫描包路径下的.class文件
            ComponentScan componentScanAnnotation =
                    (ComponentScan) appConfig.getAnnotation(ComponentScan.class);
            //路径com.cy.service
            String path = componentScanAnnotation.value();
            path = path.replace(".","/");

            ClassLoader classLoader =
                    WdpApplicationContext.class.getClassLoader();
            //E:\TCGBIII/CODE/wdpSpring/com/cy/service
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());
            
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    String fileName = f.getAbsolutePath();
                    if(fileName.endsWith(".class")){

                        String classPath =
                                fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                        classPath = classPath.replace("\\",".");
                        try {
                            Class<?> aClass = classLoader.loadClass(classPath);
                            if (aClass.isAnnotationPresent(Component.class)) {

                                if(BeanPostProcessor.class.isAssignableFrom(aClass)){
                                    BeanPostProcessor instance = (BeanPostProcessor)aClass.newInstance();
                                    beanPostProcessors.add(instance);
                                }
                                Component component = aClass.getAnnotation(Component.class);
                                String beanName = component.value();
                                if(beanName.equals("")){
                                    beanName = Introspector.decapitalize(aClass.getSimpleName());
                                }
                                BeanDefinition beanDefinition = new BeanDefinition();
                                beanDefinition.setType(aClass);
                                if(aClass.isAnnotationPresent(Scope.class)){
                                    Scope annotation = aClass.getAnnotation(Scope.class);
                                    beanDefinition.setScope(annotation.value());
                                }else{
                                    beanDefinition.setScope("singleton");
                                }
                                beanDefinitionMap.put(beanName,beanDefinition);
                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            String scope = beanDefinition.getScope();
            if(scope.equals("singleton")){
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName,bean);
            }
        }

    }

    private Object createBean(String beanName,BeanDefinition beanDefinition){
        Class type = beanDefinition.getType();
        try {
            Object bean = type.getConstructor().newInstance();
            //依赖注入
            Field[] fields = type.getDeclaredFields();
            for (Field f : fields) {
                if(f.isAnnotationPresent(Autowired.class)){
                    f.setAccessible(true);
                    f.set(bean,getBean(f.getName()));
                }
            }

            if(bean instanceof BeanNameAware){
                ((BeanNameAware)bean).setBeanName(beanName);
            }

            for (BeanPostProcessor processor : beanPostProcessors) {
                bean = processor.beanPostProcessorBeforeInit(beanName, bean);
            }

            if(bean instanceof InitializingBean){
                ((InitializingBean)bean).afterPerpertiesSet();
            }

            for (BeanPostProcessor processor : beanPostProcessors) {
                bean = processor.beanPostProcessorAfterInit(beanName,bean);
            }

            return bean;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Object getBean(String beanName){
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if(beanDefinition==null){
            throw new NullPointerException();
        }else {
            String scope = beanDefinition.getScope();
            if(scope.equals("singleton")){
                //从单例池中获取，如果不存在，则重新生成并放入池中
                Object bean = singletonObjects.get(beanName);
                if(bean==null){
                    //创建bean,并放入池中
                    Object o = createBean(beanName, beanDefinition);
                    singletonObjects.put(beanName,bean);
                }
                return bean;
            }else {
                //创建bean
                Object bean = createBean(beanName, beanDefinition);
                return bean;
            }
        }
    }

}
